package com.lgs.common.widgets.xlist;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

/**
 * @param <T> 数据类型
 */
public class BaseListAdapter<T> extends BaseAdapter {
    protected Context context;
    protected int layout;
    protected ArrayList<T> srcTable;
    protected Class<? extends BaseListItem> clazz;


    public BaseListAdapter(Context context, int layout, Class<? extends BaseListItem> clazz, List<T> dataList) {
        this.context = context;
        this.layout = layout;
        this.srcTable = (ArrayList<T>) dataList;
        this.clazz = clazz;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        BaseListItem ll;//parent代表xlistview实例
        if (convertView != null) {
            ll = (BaseListItem) convertView.getTag();
        } else {
             ll = newInstanceByConstructor(parent);
            convertView = ll.itemView;
            convertView.setTag(ll);
        }

        T item = srcTable.get(position);
        ll.setListItem(position,item,onClickListener);// 关键点，需要一个真正的对应值

        return convertView;
    }

    private BaseListItem newInstanceByConstructor(ViewGroup parent){
        BaseListItem a1 = null;
        try {
            Constructor c1=clazz.getDeclaredConstructor(Context.class,int.class,ViewGroup.class);
            c1.setAccessible(true);
            a1=(BaseListItem)c1.newInstance(new Object[]{context, layout,parent});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a1;
    }

    public int getCount() {
        return srcTable.size();
    }

    public T getItem(int position) {
        T item = srcTable.get(position);
        return item;
    }

    public long getItemId(int position) {
        return position;//暂时使用position
    }

    private IOnClickItemListener onClickListener;
    public void setOnClickItemListener(IOnClickItemListener onClickListener) {
        this.onClickListener = onClickListener;
    }
}

